class Request < ActiveRecord::Base
  has_attached_file :file

  before_update :set_valid_content_type

  
  def getlink     
    '/files/'+ id.to_s+'/original/' + file_file_name
  end
  
  def get_full_link     
    "#{RAILS_ROOT}/public" + getlink
  end
  
  def pretty_size
    gb = 1000000000
    mb = 1000000
    kb = 1000
    size = file_file_size
    
    if size > gb
      (size / gb).to_s + 'GB'
    else
      if size > mb
        (size / mb).to_s + 'MB'
      else
        if size > kb
          (size / kb).to_s + 'KB'
        else       
          size.to_s + ' bytes'
        end  
      end    
    end
  end
  
  def updated_on
    updated_at.to_s(:short)
  end
  
  def created_on
    created_at.to_s(:short)
  end  
  
  def children
    Request.find_all_by_from_id(id, :order => "updated_at DESC")
  end
  
  def get_thumbnail
    filedir = File.dirname(get_full_link)
    webdir = File.dirname(getlink)
    
    i = 1
    result = ['/images/default.jpg']
    if isimage?
      thumbname = 'thumb_' + file_file_name
      
      #tiff cannot be viewed in the browser, so I use jpg thumbnail instead
      if istiff?
        thumbname = thumbname + '.jpg'
      end

      full_thumb_link = filedir + '/' + thumbname
      
      #if thumbnail doesn't exist, create it
      if not File.exists?(full_thumb_link)
        ConvertImage.create_thumbnail(get_full_link, full_thumb_link)
      end 

      result = [webdir + '/' + thumbname]
    else #not an image
      lext = self.ext 
      extdir = "#{RAILS_ROOT}/public/images/#{lext}"
      
      #use default thumbnails if needed
      if (not File.directory?(extdir)) or (lext=="")
        lext = "unknown"
        extdir = "#{RAILS_ROOT}/public/images/#{lext}"
      end
      
      i = 0
      Dir.foreach(extdir) do |file|
        if (file =~ /.*jpg/) or (file =~ /.*png/)            
          result[i] =  "/images/#{lext}/" + file                   
          i = i + 1
        end
      end      
    end
    
    result[rand(i)]
  end

  def isimage?
    (/image.*/ =~ file_content_type) or 
    (/.*bmp/ =~ file_content_type) or 
    (/.*tiff/ =~ file_content_type)
  end

  def iszip?
    (/.*zip/ =~ file_content_type) or is_openoffice?
  end

  def israr?
    /.*rar/ =~ file_content_type
  end

  def isarchive?
    iszip? or israr?
  end

  def istiff?
    /.*tiff/ =~ file_content_type
  end

  def is_plain_text?
    /text.plain.*/ =~ file_content_type
  end

  def isxml?
    is_plain_text? and (description == "XML")
  end


  def is_msword?
    /.*msword/ =~ file_content_type or 
    /Microsoft.Word.*/ =~ description or 
    /.*doc/ =~ file_content_type
  end

  def is_openoffice?
    (/.*odt/ =~ file_content_type) or
    (/OpenOffice.*Writer.*/ =~ description) or
    (/OpenOffice.*Calc.*/ =~ description) or
    ("OpenDocument Spreadsheet" == description) or
    ('OpenDocument Presentation' == description) or
    (/OpenOffice.*Impress.*/ =~ description)
  end

  def is_writer?
    is_plain_text? or 
    is_msword? or
    (/.*rtf/ =~ file_content_type) or
    (ext.downcase == 'doc' and description == 'Microsoft Office Document') or 
    ('text/html' == file_content_type) or 
    (/.*odt/ =~ file_content_type) or
    (/OpenOffice.*Writer.*/ =~ description) or 
    (iszip? and (ext.downcase == 'docx'))
  end

  def is_calc?
    (ext.downcase == 'xls' and description == 'Microsoft Office Document') or
    (/OpenOffice.*Calc.*/ =~ description) or
    ("OpenDocument Spreadsheet" == description) or 
    (iszip? and ext.downcase == 'xlsx')
  end

  def is_presentation?
    (iszip? and ext.downcase == 'pptx') or 
    ("Microsoft Office Document" == description and ext.downcase == 'ppt') or
    ('OpenDocument Presentation' == description) or 
    (/OpenOffice.*Impress.*/ =~ description)
  end
  

  def ext
    File.extname(file_file_name).delete('.').downcase
  end



  private

    # execute a sustem command, if it fails read the error file
    # and raise an exception
    def exec_to_file(acommand, afile)
      if not system(acommand + " '#{get_full_link}' >> #{afile} 2>&1")
        ferr=File.new(afile,'r')
        begin
          raise ferr.readline.delete("\n")
        ensure
          ferr.close
        end
      end      
    end

    # use the 'file' command to get mime-type and description
    def set_valid_content_type
      if new_record?
        return true
      end
      
      #fix a bug of paperclip, that uses '.'
      if (ext == "") and File.exists?(get_full_link+'.')
        File.rename(get_full_link+'.', get_full_link)
      end

      rand_file = '/tmp/ff_rand_'+rand(10000000).to_s      
      begin
        exec_to_file('file -b ',rand_file); #full description
        exec_to_file('file -i -b ',rand_file); #mime-type
        if File.exists?(rand_file)
          afile = File.new(rand_file,'r')
          begin
            self.description = afile.readline.delete "\n"
            
            if not afile.eof
              l = afile.readline.delete("\n")
              if l.length < self.file_content_type.length
                self.file_content_type = l
              end
            end           
            
            if iszip? and ext == 'docx'
              self.description = "Microsoft Word Open XML Document"
            end

            if iszip? and ext == 'xlsx'
              self.description = "Microsoft Excel Open XML Document"
            end

            if iszip? and ext == 'pptx'
              self.description = "Microsoft PowerPoint Open Xml Document"
            end
          ensure
            afile.close
          end          
        end

      ensure
        if File.exists?(rand_file)
          File.delete(rand_file)
        end  
      end
      return true
    end

end
